<template>
<div class="tw-applistbox">
  <div v-if="!disablePagination" class="tw-applist-pagination">
    <i class="icon iconfont" :class="{xdisabled: pageNo<=1}" @click="(pageNo>1 && (pageNo--))">&#xe7db;</i>
    <i class="icon iconfont" :class="{xdisabled: pageNo>=appList.length/showCounts}" @click="(pageNo<appList.length/showCounts && (pageNo++))">&#xe7dc;</i>
  </div>

  <div v-if="list && list.length>0" class="tw-applist">
    <!-- :href="href?`${href}?appId=${app.appId}`:''" -->
    <!-- :style="{width: 1 / columns*100+'%'}" -->
    <el-row :gutter="appSpacing" style="width: 100%">
      <el-col
        v-for="(app, idx) in list"
        :key="idx"
        :span="columns == 5 ? 5 : 24 / columns"
      >
        <a class="tw-applist-item" @click="toApply('应用', app.appUrl)">
          <div class="tw-applist-item-iconbox">
            <img v-if="app.logoUrl" :src="app.logoUrl.startsWith('http')?app.logoUrl:`${$twApp.gateway}/fs/media${app.logoUrl}`" />
            <img v-else-if="appImages[idx]" :src="`${$twApp.fileBaseUrl}${appImages[idx].localPath}`" />
            <img v-else src="@assets/app-default.png" />
          </div>

          <div class="tw-applist-item-body">
            <h4>{{app.appName}}</h4>
            <div class="tw-label">
              <span class="tw-label-free"
                :class="{xcolor: app.isCharge && app.isCharge !== '1'}">{{app.isCharge && app.isCharge !== '1' ? '收费' : '免费'}}</span>
              <span v-if="list[idx].appLvl" class="tw-label-icon xnational">{{app.appLvl}}</span>
            </div>
            <div class="tw-details-nav">
              <span @click.stop="toApply('详情', detailUrl, app.appId)">
                详情 >
              </span>
            </div>
          </div>
        </a>
      </el-col>
    </el-row>
  </div>

  <div v-else class="tw-libnodata"></div>
</div>
</template>

<script>
import props from './props'

export default {
  name: 'table',

  props,

  data() {
    return {
      appList: [],
      pageNo: 1,
      accessToken: '',
      usessionId: '',
      infos: {},
      lock: false
    }
  },

  computed: {
    list () {
      if (this.showCounts) {
        return this.appList.filter((item, idx) => (this.pageNo - 1) * this.showCounts <= idx && idx < this.pageNo * this.showCounts)
      } else {
        return this.appList
      }
    },

    style () {
      return {
        borderColor: this.borderColor,
        iconSize: this.iconSize,
        nameFontSize: this.nameFontSize,
        nameColor: this.nameColor,
        linkFontSize: this.linkFontSize,
        linkColor: this.linkColor,
        hoverColor: this.hoverColor,
        paginationColor: this.paginationColor,
        paginationSize: this.paginationSize,
        paginationHoverColor: this.paginationHoverColor,
        appSpacing: this.appSpacing,
        bgColor: this.bgColor,
        backUrl: this.backUrl,
        detailUrl: this.detailUrl
      }
    }
  },

  methods: {
    setStyle () {
      const style = `
        ::root .tw-applist {
          border-top-color: ${this.borderColor};
          border-left-color: ${this.borderColor};
        }

        ::root .tw-applist-item {
          border-right-color: ${this.borderColor};
          border-bottom-color: ${this.borderColor};
          background-color: ${this.bgColor};
        }

        ::root .tw-applist-item-iconbox {
          width: ${this.iconSize};
          min-width: ${this.iconSize};
          height:${this.iconSize};
        }

        ::root .tw-applist-item-body > h4 {
          font-size: ${this.nameFontSize};
          color: ${this.nameColor};
        }

        ::root .tw-applist-item-body > div {
          font-size: ${this.linkFontSize};
          color: ${this.linkColor};
        }

        ::root .tw-applist-item-body > div > i {
          border-right-color: ${this.linkColor};
          border-bottom-color: ${this.linkColor};
        }

        ::root .tw-applist-item:hover .tw-applist-item-body > h4,
        ::root .tw-applist-item:hover .tw-applist-item-body > div {
          color: ${this.hoverColor};
        }

        ::root .tw-applist-item:hover .tw-applist-item-body > div > i  {
          border-right-color: ${this.hoverColor};
          border-bottom-color: ${this.hoverColor};
        }

        ::root .tw-applist-pagination .iconfont {
          color: ${this.paginationColor};
          font-size: ${this.paginationSize};
        }

        ::root .tw-applist-pagination .iconfont:hover {
          color: ${this.paginationHoverColor};
        }
      `

      this.addStyle(style)
    },

    addStyle (style) {
      this.$el.classList.add(`x${this._uid}`)
      const styleEl = document.getElementById(this._uid) || document.createElement('style')
      styleEl.id = this._uid
      styleEl.innerText = style.replace(/::root/gm, `.x${this._uid}`).replace(/\n/gm, '')

      document.head.appendChild(styleEl)
    },

    getAppList () {
      // window.axios.defaults.headers.common['Access-Token'] = '47e500275a77f2e2626cd8f067541416'
      // window.axios.defaults.headers.common['Current-Org-Id'] = 'TWPAAS1200000081829'
      // window.axios.defaults.headers.common['Tenant-Id'] = 'BJ00002'
      window.axios.post(`${window.$twApp.gateway}/openapi-uc/app/recommend/list`, {}).then(resp => {
        if (resp.data.serverResult.resultCode && resp.data.pageInfo && resp.data.pageInfo.list) {
          this.appList = resp.data.pageInfo.list.map((item, idx) => {
            return {
              id: item.appId,
              name: item.appName,
              url: item.callbackUrl,
              addAccreditCode: true,
              img: item.icon1 ? `${this.$twApp.gateway}/fs/media${item.icon1}` : ''
            }
          })
        } else {
          console.log('调用失败')
          // this.$ui.msg({
          //   type: 'error',
          //   message: '错误应用列表失败'
          // })
        }
      }).catch(e => {
        console.log('调用失败')
        // this.$ui.msg({
        //   type: 'error',
        //   message: '错误应用列表失败'
        // })
      })
    },

    // 进入应用获取票据信息
    toApply (types, app, appId) {
      if (!this.lock) {
        this.lock = true
      } else {
        return false
      }
      // 调用获取票据通行证
      window.axios.post(`${window.$twApp.gateway}/openapi-nationalresource/application/validateCertification`,
        { userId: this.$twApp.user.userId, loginName: this.$twApp.user.loginName })
        .then(resp => {
          if (resp.data && resp.data.responseEntity) {
            window.axios.post(`${window.$twApp.gateway}/openapi-nationalresource/application/createTicket`,
              { accessToken: resp.data.responseEntity.accessToken, usessionId: resp.data.responseEntity.usessionId })
              .then(info => {
                if (info.data && info.data.responseEntity) {
                  this.infos = info.data.responseEntity
                  if (types === '应用') {
                    window.open(`${app + '&ticket=' + this.infos.ticket + '&sysCode=' + this.infos.sysCode}`)
                    this.lock = false
                  } else if (types === '详情') {
                    window.location.href = `${app + '?appId=' + appId + '&accessToken=' + resp.data.responseEntity.accessToken}`
                    this.lock = false
                  }
                }
              }).catch(() => {
                console.log('调用票据接口失败')
                this.lock = false
              })
          }
        }).catch(() => {
          console.log('调用实名认证接口失败')
          this.lock = false
        })
    },

    // 验证用户是否实名认证
    isApprove () {
      const vm = this
      window.axios.post(`${window.$twApp.gateway}/openapi-nationalresource/application/validateCertification`,
        { userId: this.$twApp.user.userId, loginName: this.$twApp.user.loginName }).then(resp => {
        if (resp.data && resp.data.responseEntity) {
          if (resp.data.responseEntity.retCode === '000000') { // 表示已认证成功
            this.accessToken = resp.data.responseEntity.accessToken
            this.usessionId = resp.data.responseEntity.usessionId
            this.getApplicationList() // 已认证调用应用列表
          } else if (resp.data.responseEntity.retCode === '300027') { // 该用户未实名请跳转实名页面进行认证
            this.$confirm('该用户未实名请跳转实名页面进行验证', '提示', {
              closeOnClickModal: false,
              confirmButtonText: '去实名认证',
              cancelButtonText: '取消'
            }).then(() => {
              window.open(`${resp.data.responseEntity.certUrl}`) // 未实名认证的跳转地址
              window.location.href = vm.backUrl // 跳去验证当前页面回到前面
            }).catch(() => {
              window.location.href = vm.backUrl // 取消后回到配置地址
            })
          }
        } else {
          console.log('接口调用失败')
        }
      })
    },

    // 获取国家公共应用信息列表
    getApplicationList () {
      window.axios.post(`${window.$twApp.gateway}/openapi-nationalresource/application/queryApplicationList`,
        { accessToken: this.accessToken, usessionId: this.usessionId, pageNo: 1, numPerPage: 200 }).then(resp => {
        if (resp.data && resp.data.responseEntity) {
          this.appList = resp.data.responseEntity
        }
      })
    }
  },

  created () {
    // 验证是否实名认证
    this.isApprove()

    if (this.appType === '1') {
      this.getAppList()
    } else {
      // 如果是外部应用直接调用已认证的信息列表接口 // this.appList = this.data
    }
  },

  mounted () {
    this.setStyle()
  },

  watch: {
    style: {
      deep: true,
      handler () {
        this.setStyle()
      }
    },

    appType (val) {
      if (val === '1') {
        this.getAppList()
      } else {
        this.appList = this.data
      }
    },

    data: {
      deep: true,
      handler () {
        this.appList = this.data
      }
    }
  }
}
</script>

<style lang="scss">
  @import './css/index.scss';
</style>
